#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "characterset.h"
#include "buffer.h"

int TestASCII2UTF8( const char * filepath );
int TestUTF82ASCII( const char * filepath );
int TestBuffer()
{
	Buffer inbuf;
	Buffer outbuf;
	char in[] = {"hello,word你好"};
	inbuf.Append( in, sizeof(in) );
	int ret = CharacterSetTransform::Transform( &inbuf, "UTF-8", &outbuf, "gb2312");
	printf( "%s\n", outbuf.GetByteBuffer() );

	return ret;
}

int main( int argc, char * argv[] )
{

	if ( argc < 2 )
	{
		printf("./testcharacterset <file> <mode>\n");
		printf(" <mode> 1 test ascii 2 utf-8\n");
		printf(" <mode> 2 test utf-8 2 ascii\n");
		exit(1);
	}
	printf("%s, %s\n",argv[1], argv[2]);
	const char * filepath = argv[1];
	const int mode = atoi( argv[2] );
	int ret = -1;
	switch( mode )
	{
		case 1:
			ret = TestASCII2UTF8( filepath );
			break;
		case 2:
			ret = TestUTF82ASCII( filepath );
			break;
		case 3:
			ret = TestBuffer();
			break;
		default:
			printf("unknow mode\n");
	}
	printf( "ret is %d\n", ret );
	return ret;
}

int Getfilebuf( const char * filepath, char * & buf, size_t & buflen )
{
	int endpos = -1, len = -1, ret = -1;
	char * tmpBuf = NULL;
	FILE * fp = fopen( filepath, "r" );

	if ( NULL != fp )
	{
		fseek( fp, 0, SEEK_END );
		endpos = ftell( fp );
		fseek( fp, 0, SEEK_SET );
		tmpBuf = new char[ endpos + 1 ];
		memset( tmpBuf, 0, endpos+1 );
		
		len = fread( tmpBuf, 1, endpos+1, fp );

		if ( len == endpos )
		{
			buf = tmpBuf;
			buflen = len;
			ret = 0;
		}
		else
		{
			printf("len != endpos , len %d endpos %d\n",len, endpos);
		}
	}
	else
		printf("fp == NULL");
	return ret;
}

int TestASCII2UTF8( const char * filepath )
{
	int ret = -1;
    size_t inlen = 0, outlen = 0;
	char * outbuf = NULL;
	if ( NULL != filepath )
	{
		char inbuf[] = {"hello,word"};
	    inlen = strlen(inbuf);	
		ret = 0;
		//ret = Getfilebuf( filepath, inbuf, inlen );
		if ( 0 == ret )
		{
			outlen = inlen*10;
			outbuf = new char [ outlen ];
			memset( outbuf, 0, outlen );
			ret = CharacterSetTransform::Transform( inbuf, inlen, "ASCII",
				outbuf, outlen, "UTF-8");
			printf("Transform ret %d\n",ret);
			if ( 0 == ret )//output to a file
			{
				printf("%s\n",outbuf);
			}
		}
	}
	return ret;
}

int TestUTF82ASCII( const char * filepath )
{
	return 0;
}






